﻿using ApplicationBase.Core.Domain;
using IdentityService.Domain.Aggregates.RoleAggregate;
using System.Text;

namespace IdentityService.Domain.Aggregates.UserAccountAggregate
{
    public class UserAccount : Entity, IAggregateRoot
    {
        public long Id { get; init; }
        public string UserName { get; private set; }
        private string PasswordHash;
        private string SecurityStamp;
        public string? Email { get; private set; }
        public string? PhoneNumber { get; private set; }
        public DateTime? LockoutUntil { get; private set; }
        public int AccessFailedCount { get; set; }
        public DateTime CreateTime { get; init; }
        public UserInfo UserInfo { get; private set; }
        public List<Role> Roles { get; private set; } = new();
        public List<UserAccountClaim> Claims { get; private set; } = new();

        #pragma warning disable CS8618
        private UserAccount() { }
        #pragma warning restore CS8618 
        public UserAccount(long id, string userName, string password)
        {
            Id = id;
            UserName = userName;
            SecurityStamp = Guid.NewGuid().ToString().Replace("-", "");
            PasswordHash = GetPasswordHash(password);
            CreateTime = DateTime.UtcNow;
            UserInfo = new UserInfo(id);
        }

        public bool CheckPassword(string password)
        {
            return GetPasswordHash(password) == PasswordHash;
        }

        public void Lockout(DateTime lockoutUntil)
        {
            AccessFailedCount = 0;
            LockoutUntil = lockoutUntil;
        }

        public void UnLock()
        {
            AccessFailedCount = 0;
            LockoutUntil = null;
        }

        public void ModifyPassword(string password)
        {
            PasswordHash = GetPasswordHash(password);
        }

        private string GetPasswordHash(string password)
        {
            return Convert.ToBase64String(Encoding.UTF8.GetBytes($"{password}{SecurityStamp}"));
        }
    }
}
